package cn.demoframe.test.frame.controller;

import cn.demoframe.test.frame.model.MenuInfo;
import cn.demoframe.test.frame.model.RoleInfo;
import cn.demoframe.test.frame.model.UserInfo;
import cn.demoframe.test.frame.service.MenuinfoService;
import cn.demoframe.test.frame.service.RoleinfoService;
import cn.demoframe.test.frame.service.UserinfoService;
import cn.demoframe.test.model.Message;
import cn.demoframe.test.model.Treenode;
import cn.demoframe.test.utils.Constants;
import cn.demoframe.test.utils.CryptToolkit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class FrameController {
    private static final Logger logger = LoggerFactory.getLogger(Thread
            .currentThread().getStackTrace()[1].getClassName());

    @Resource(name = "UserinfoServiceImpl")
    private UserinfoService userinfoService;

    @Resource(name = "RoleinfoServiceImpl")
    private RoleinfoService roleinfoService;
    
    @Resource(name = "MenuinfoServiceImpl")
    private MenuinfoService menuinfoService;

    /**
     * 系统登录
     * @param request 请求
     * @param username 用户名
     * @param password 密码
     * @return 地址
     */
    @RequestMapping(value = { "/sys/login" }, method = { RequestMethod.POST })
    public String login_log(HttpServletRequest request,
              @RequestParam(value = "username") String username,
              @RequestParam(value = "password") String password) {
        String retUrl = "/frame/jump";

        List<UserInfo> list = userinfoService.getUserInfos(null, username,
        		null, null, null, null, null, null, null);
        
        if (null != list && list.size() > 0 && CryptToolkit.getJavaMD5(CryptToolkit.base643DesEncoder(password,
                Constants.ENCRYPTKEY)).equals(list.get(0).getPasswd())) {
    		HttpSession session = request.getSession();
    		UserInfo user = list.get(0);
            logger.debug("login : " + user.getUserid());
    		session.setAttribute("LOGIN_USER", user.getUserid());
    		session.setAttribute("LOGIN_NAME", user.getUsernm());
    		session.setAttribute("LOGIN_ROLE", user.getRoleid());
    		session.setAttribute("LOGIN_FLAG", "SUCC");
        } else {
            retUrl = "/frame/loginerror";
        }

        return retUrl;
    }

    @RequestMapping(value = "/sys/logout", method = RequestMethod.GET)
    public String Logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();
        return "/frame/login";
    }

    /**
     * 获取登录状态（是否超时）
     * @param request 请求
     * @return 信息
     */
    @RequestMapping(value = { "/sys/frame/sessionstatus" }, method = { RequestMethod.POST })
    @ResponseBody
    public Message getSessionStatus(HttpServletRequest request) {
        Message m = new Message();
        if (request.isRequestedSessionIdValid()) {
            m.setResult("0");
            m.setDetail("会话未超时.");
        } else {
            m.setResult("1");
            m.setDetail("会话已超时.");
        }
        return m;
    }

    /**
     * 获取功能菜单节点
     * @return 节点
     */
    @RequestMapping(value = "/sys/frame/getmenunodes", method = RequestMethod.POST)
    @ResponseBody
    public List<Treenode> getMenuNodes(HttpServletRequest request) {
        logger.debug("获取功能菜单节点");
        HttpSession session = request.getSession();
        String loginrole = (String) session.getAttribute("LOGIN_ROLE");
        RoleInfo r = roleinfoService.getRoleInfos(loginrole,
                null, null).get(0);
        String lmt = r.getLmtserial();
        List<Treenode> nodelist;
        List<MenuInfo> tmpnodes = menuinfoService.getMenuInfos(null, null,
        		null, "position ");
        List<Treenode> tree = new ArrayList<Treenode>();
        Treenode tn;
        for(MenuInfo t : tmpnodes){           
            if(t.getNodetype().equals("0")){
                tn = new Treenode();
                tn.setName(t.getTitle());
                tn.setId(t.getMenuid().toString());
                Map<String, Object> attr = new HashMap<String, Object>();
                attr.put("type", t.getNodetype());
                attr.put("parentid", t.getParentid());
                attr.put("url", t.getUrl());
                tn.setAttributes(attr);
                nodelist = new ArrayList<Treenode>();
                for(MenuInfo t2 : tmpnodes){
                    if(t.getMenuid().equals(t2.getParentid()) &&
                            lmt.charAt(t2.getMenuid()) == '1' ){
                        Treenode tnode = new Treenode();
                        tnode.setId(t2.getMenuid().toString());
                        tnode.setName(t2.getTitle());
                        Map<String, Object> attr1 = new HashMap<String, Object>();
                        attr1.put("type", t2.getNodetype());
                        attr1.put("parentid", t2.getParentid());
                        attr1.put("url", t2.getUrl());
                        tnode.setAttributes(attr1);
                        nodelist.add(tnode);
                    }
                }
                if(nodelist.size() > 0){
                	tn.setChildren(nodelist);
                    tree.add(tn);
                }
            }           
        }
        return tree;
    }
}
